"""
消息服务
"""
from flask_login import current_user
from datetime import datetime
from app.models import Message, MessageRecipient, MessageTemplate, User, get_db
from app import db

class MessageService:
    """消息服务类"""
    
    @staticmethod
    def create_message(title, content, message_type, sender_id=None, receiver_id=None, 
                      priority='普通', target_type=None, target_id=None):
        """创建单条消息"""
        db = get_db()
        
        # 如果没有指定发送者，使用当前用户
        if sender_id is None and current_user.is_authenticated:
            sender_id = current_user.id
        
        message = Message(
            title=title,
            content=content,
            message_type=message_type,
            priority=priority,
            sender_id=sender_id,
            receiver_id=receiver_id,  # 使用receiver_id而不是recipient_id
            target_type=target_type,
            target_id=target_id
        )
        
        db.session.add(message)
        db.session.commit()
        
        return message
    
    @staticmethod
    def create_bulk_message(title, content, message_type, sender_id=None, recipient_ids=None, 
                           priority='普通', target_type=None, target_id=None):
        """批量创建消息（群发）"""
        db = get_db()
        
        # 如果没有指定发送者，使用当前用户
        if sender_id is None and current_user.is_authenticated:
            sender_id = current_user.id
        
        # 由于数据库要求receiver_id非空，使用第一个接收者作为receiver_id
        primary_receiver_id = recipient_ids[0] if recipient_ids else sender_id
        
        # 创建主消息记录（指定第一个接收者作为receiver_id）
        message = Message(
            title=title,
            content=content,
            message_type=message_type,
            priority=priority,
            sender_id=sender_id,
            receiver_id=primary_receiver_id,  # 使用第一个接收者作为receiver_id
            target_type=target_type,
            target_id=target_id
        )
        
        db.session.add(message)
        db.session.flush()  # 获取message.id
        
        # 为每个接收者创建接收记录（包括第一个接收者）
        if recipient_ids:
            for recipient_id in recipient_ids:
                recipient = MessageRecipient(
                    message_id=message.id,
                    user_id=recipient_id
                )
                db.session.add(recipient)
        
        db.session.commit()
        
        return message
    
    @staticmethod
    def send_message_from_template(template_name, recipient_ids=None, sender_id=None, 
                                  target_type=None, target_id=None, **kwargs):
        """从模板发送消息"""
        template = MessageTemplate.get_by_name(template_name)
        
        if not template:
            raise ValueError(f"消息模板 '{template_name}' 不存在或已禁用")
        
        # 渲染模板
        title, content = template.render(**kwargs)
        
        # 如果是单个接收者，使用单条消息
        if recipient_ids and len(recipient_ids) == 1:
            return MessageService.create_message(
                title=title,
                content=content,
                message_type=template.message_type,
                sender_id=sender_id,
                receiver_id=recipient_ids[0],
                priority=template.priority,
                target_type=target_type,
                target_id=target_id
            )
        # 否则使用批量消息
        else:
            return MessageService.create_bulk_message(
                title=title,
                content=content,
                message_type=template.message_type,
                sender_id=sender_id,
                recipient_ids=recipient_ids,
                priority=template.priority,
                target_type=target_type,
                target_id=target_id
            )
    
    @staticmethod
    def send_template_message(template_name, recipient_ids=None, sender_id=None, 
                             related_type=None, related_id=None, **kwargs):
        """从模板发送消息（send_message_from_template的别名，用于兼容现有代码）
        
        Args:
            template_name: 模板名称
            recipient_ids: 接收者ID列表
            sender_id: 发送者ID
            related_type: 关联对象类型（兼容参数，映射到target_type）
            related_id: 关联对象ID（兼容参数，映射到target_id）
            **kwargs: 其他参数
            
        Returns:
            创建的消息对象
        """
        # 将related_type和related_id映射到target_type和target_id
        target_type = related_type
        target_id = related_id
        
        # 调用send_message_from_template方法
        return MessageService.send_message_from_template(
            template_name=template_name,
            recipient_ids=recipient_ids,
            sender_id=sender_id,
            target_type=target_type,
            target_id=target_id,
            **kwargs
        )
    
    @staticmethod
    def get_user_messages(user_id, page=1, per_page=10, unread_only=False):
        """获取用户消息列表"""
        # 获取直接发送给用户的消息
        direct_messages = Message.query.filter_by(receiver_id=user_id)
        
        # 获取群发给用户的消息
        bulk_message_ids = db.session.query(MessageRecipient.message_id).filter_by(user_id=user_id).subquery()
        bulk_messages = Message.query.filter(Message.id.in_(db.session.query(bulk_message_ids)))
        
        # 合并查询
        query = direct_messages.union(bulk_messages)
        
        if unread_only:
            # 对于直接消息，检查is_read字段
            direct_unread = direct_messages.filter_by(is_read=False)
            # 对于群发消息，检查MessageRecipient表中的is_read字段
            bulk_unread = bulk_messages.join(MessageRecipient).filter_by(is_read=False)
            query = direct_unread.union(bulk_unread)
            
        return query.order_by(Message.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
    
    @staticmethod
    def get_unread_count(user_id):
        """获取用户未读消息数量"""
        db = get_db()
        
        # 直接发送给用户的未读消息
        direct_unread = Message.query.filter_by(
            receiver_id=user_id, 
            is_read=False
        ).count()
        
        # 群发给用户的未读消息
        bulk_message_ids = db.session.query(MessageRecipient.message_id).filter_by(
            user_id=user_id, 
            is_read=False
        ).subquery()
        bulk_unread = Message.query.filter(Message.id.in_(db.session.query(bulk_message_ids))).count()
        
        return direct_unread + bulk_unread
    
    @staticmethod
    def mark_message_as_read(user_id, message_id):
        """标记消息为已读"""
        db = get_db()
        
        # 检查是否是直接发送给用户的消息
        message = Message.query.filter_by(id=message_id, receiver_id=user_id).first()
        if message:
            message.mark_as_read()
            return True
        
        # 检查是否是群发给用户的消息
        recipient = MessageRecipient.query.filter_by(
            message_id=message_id, 
            user_id=user_id
        ).first()
        if recipient:
            recipient.mark_as_read()
            return True
            
        return False
    
    @staticmethod
    def mark_all_as_read(user_id):
        """标记所有消息为已读"""
        db = get_db()
        
        # 标记直接发送给用户的消息为已读
        direct_messages = Message.query.filter_by(receiver_id=user_id, is_read=False).all()
        for message in direct_messages:
            message.mark_as_read()
        
        # 标记群发给用户的消息为已读
        recipients = MessageRecipient.query.filter_by(user_id=user_id, is_read=False).all()
        for recipient in recipients:
            recipient.mark_as_read()
        
        return True
    
    @staticmethod
    def get_admins_and_sales_leads():
        """获取所有管理员和销售部门领导的ID列表"""
        db = get_db()
        
        # 获取管理员
        admins = User.query.filter_by(role='admin').all()
        admin_ids = [admin.id for admin in admins]
        
        # 获取销售部门领导（假设职位包含"经理"、"主管"、"总监"等关键词）
        sales_leads = User.query.filter(
            User.department.like('%销售%'),
            User.position.in_(['经理', '主管', '总监', '部长'])
        ).all()
        sales_lead_ids = [lead.id for lead in sales_leads]
        
        # 合并并去重
        return list(set(admin_ids + sales_lead_ids))
    
    @staticmethod
    def get_admin_ids():
        """获取管理员ID列表"""
        db = get_db()
        # 查询角色为admin的用户
        admins = User.query.filter(
            User.is_active == True,
            User.role == 'admin'
        ).all()
        return [user.id for user in admins]
    
    @staticmethod
    def get_sales_leader_ids():
        """获取销售部门领导ID列表"""
        db = get_db()
        # 查询销售部门且职位为领导的用户
        sales_leaders = User.query.filter(
            User.is_active == True,
            User.department.like('%销售%'),
            User.position.in_(['经理', '主管', '总监', '部长'])
        ).all()
        return [user.id for user in sales_leaders]
    
    @staticmethod
    def create_default_templates():
        """创建默认消息模板"""
        db = get_db()
        
        # 检查是否已存在默认模板
        existing_templates = MessageTemplate.query.filter_by(name='customer_created').first()
        if existing_templates:
            return
        
        # 创建客户创建通知模板
        customer_created_template = MessageTemplate(
            name='customer_created',
            message_type='通知',
            priority='普通',
            title_template='新客户创建通知 - {customer_name}',
            content_template='''尊敬的领导：

员工 {employee_name}（{department}）于 {date} {time} 创建了新客户，详细信息如下：

客户名称：{customer_name}
客户编号：{customer_code}
客户类型：{customer_type}
创建时间：{datetime}

请及时关注新客户信息。

系统自动发送''',
            recipient_type='指定用户',
            is_active=True
        )
        
        # 创建客户更新通知模板
        customer_updated_template = MessageTemplate(
            name='customer_updated',
            message_type='通知',
            priority='普通',
            title_template='客户信息更新通知 - {customer_name}',
            content_template='''尊敬的领导：

员工 {employee_name}（{department}）于 {date} {time} 更新了客户信息，详细信息如下：

客户名称：{customer_name}
客户编号：{customer_code}
客户类型：{customer_type}
更新时间：{datetime}

请及时关注客户信息变更。

系统自动发送''',
            recipient_type='指定用户',
            is_active=True
        )
        
        # 创建跟进记录通知模板
        followup_created_template = MessageTemplate(
            name='followup_created',
            message_type='通知',
            priority='普通',
            title_template='客户跟进记录 - {customer_name}',
            content_template='''尊敬的领导：

员工 {employee_name}（{department}）于 {date} {time} 对客户进行了跟进，详细信息如下：

客户名称：{customer_name}
客户编号：{customer_code}
跟进时间：{datetime}

请及时关注客户跟进情况。

系统自动发送''',
            recipient_type='指定用户',
            is_active=True
        )
        
        db.session.add_all([
            customer_created_template,
            customer_updated_template,
            followup_created_template
        ])
        db.session.commit()